package CustomUI;

import java.util.ArrayList;
import java.util.List;

import org.Consts;
import org.Globals;
import org.Utility;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.dworld3.Draw;

import com.ydev.dworld3.R;

import DTO.FavouriteColorDTO;
import DTO.ObjectDTO;
import GameTools.ydPoint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.LinearLayout.LayoutParams;

public class ydCustomColorPicker extends Dialog {

	ydPoint size;

	ydColorLineMajor s1 = new ydColorLineMajor(this.getContext());
	ydColorLineMinor s2 = new ydColorLineMinor(this.getContext());

	SeekBar sbRed = new SeekBar(this.getContext());
	SeekBar sbGreen = new SeekBar(this.getContext());
	SeekBar sbBlue = new SeekBar(this.getContext());
	SeekBar sbAlpha = new SeekBar(this.getContext());

	View v1 = new View(this.getContext());

	Button btnSave;

	ScrollView svFavColorsView;
	LinearLayout LLFavColorsHolder;

	ArrayList<FavouriteColorDTO> favColors = new ArrayList<FavouriteColorDTO>();

	ArrayList<LinearLayout> favColorsRows = new ArrayList<LinearLayout>();
	List<View> allViews;

	Boolean didAddColor=false;
	Context mContext;
	
	public ydCustomColorPicker(Context context) {
		super(context);
		mContext=context;
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.color_dialog_layout);

		favColors = FavouriteColorDTO.getObjectsInDatabase(Globals.sqlDB);

		setupScreen();

		s1 = (ydColorLineMajor) findViewById(R.id.ydColorLineMajor1);
		s2 = (ydColorLineMinor) findViewById(R.id.ydColorLineMinor1);

		v1 = (View) findViewById(R.id.selectedColor);
		v1.setBackgroundColor(s1.getCurrentMainColor());

		btnSave = (Button) findViewById(R.id.btnColorSave);

		btnSave.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				FavouriteColorDTO fav = new FavouriteColorDTO();
				Bitmap viewCapture = Utility.ViewToBitmap(v1);
				int pixel = viewCapture.getPixel(10,10);
				fav.colorValue =pixel;
				fav.image = Bitmap.createBitmap(v1.getWidth(), v1.getHeight(),
						Bitmap.Config.ARGB_8888);
				Canvas canvas = new Canvas(fav.image);
				v1.draw(canvas);

				fav.insertIntoDatabase(Globals.sqlDB);
				favColors.add(fav);
				setupScreen();

			}
		});
		
		ydButton btn=(ydButton)findViewById(R.id.ydButtonOK);
		btn.addOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				((Draw)mContext).ColorSelected(s1.getSelectedColor());
				hide();
			}
		});
		
		setTouchListeners();

	}

	public ydCustomColorPicker(Context context, int theme) {
		super(context, theme);
		// TODO Auto-generated constructor stub
	}

	public ydCustomColorPicker(Context context, boolean cancelable,
			OnCancelListener cancelListener) {
		super(context, cancelable, cancelListener);
		// TODO Auto-generated constructor stub
	}

	private void setTouchListeners() {
		s2.listeners.addOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				s1.updateCurrentSelectedColor(s2.getCurrentHue());
				v1.setBackgroundColor(s1.getSelectedColor());
				// s2.setVisibility(View.INVISIBLE);
				// s1.setColor(r,g,b);
				// s1.setCurrentHue(s2.getCurrentHue());
				// s1.setChangeMade(true);
				return true;
			}
		});

		s1.listeners.addOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				float x = event.getX();
				float y = event.getY();
				
				s1.picked.setCoordinates(new ydPoint(x, y));
				s1.invalidate();
				v1.setBackgroundColor(s1.getColor((int)x, (int)y));
				return true;
			}
		});

	}

	private Handler mHandler = new Handler();

	public void setupScreen() {

		svFavColorsView = (ScrollView) findViewById(R.id.scrollViewFavColors);
		LLFavColorsHolder = (LinearLayout) findViewById(R.id.LLFavColorsHolder);

		// loadFavColors();
		//loadFavColors2();

		// new loadFavAsync().execute();

		mHandler.postDelayed(runnable, 1);

	}

	private Runnable runnable = new Runnable() {
		public void run() {
			allViews = new ArrayList<View>();

			LinearLayout imageLayout = new LinearLayout(getContext());
			imageLayout.setOrientation(LinearLayout.HORIZONTAL);
			imageLayout.setLayoutParams(new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT));

			if (favColors != null) {
				View v = null;
				for (int i = 0; i < favColors.size(); i++) {

					v = new View(getContext());
					LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(
							50, 50);
					par.setMargins(10, 0, 0, 10);
					// v.setLayoutParams(par);

					v.setBackgroundColor(favColors.get(i).colorValue);
					v.setTag(i);
					v.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							int x = (Integer) v.getTag();
							v1.setBackgroundColor(favColors.get(x).colorValue);

						}
					});
					
					v.setOnLongClickListener(new OnLongClickListener() {
				        public boolean onLongClick(View v) {
				        	int x = (Integer) v.getTag();
				        	favColors.get(x).removeFromDB(Globals.sqlDB);
				        	favColors = FavouriteColorDTO.getObjectsInDatabase(Globals.sqlDB);
				        	setupScreen();
				            return true;
				        }
				    });
					v.setLayoutParams(par);

					allViews.add(v);
				}

			} else {
				Log.d("", "== image list was null");
			}

			try {

				if (LLFavColorsHolder.getChildCount() > 0)
					LLFavColorsHolder.removeAllViews();

				/*
				 * Display display = getWindowManager() .getDefaultDisplay();
				 */
				int maxWidth = LLFavColorsHolder.getWidth();

				LinearLayout newLL = new LinearLayout(getContext());
				newLL.setLayoutParams(new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
				newLL.setGravity(Gravity.LEFT);
				newLL.setOrientation(LinearLayout.HORIZONTAL);

				int widthSoFar = 0;
				int imageSize = maxWidth / 4 - 3;
				LayoutParams lp = new LayoutParams(imageSize, imageSize);
				LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(
						40, 40);
				par.setMargins(10, 0, 0, 10);
				for (int i = 0; i < allViews.size(); i++) {

					allViews.get(i).measure(0, 0);

					widthSoFar += imageSize;// allViews.get(i).getMeasuredWidth();

					Log.d("", "== widthSoFar is " + String.valueOf(widthSoFar));
					Log.d("", "== maxWidth is " + String.valueOf(maxWidth));
					if (newLL.getChildCount()==5) {
						LLFavColorsHolder.addView(newLL);
						Log.d("", "== a new row");

						newLL = new LinearLayout(getContext());
						newLL.setLayoutParams(new LayoutParams(
								LayoutParams.FILL_PARENT,
								LayoutParams.WRAP_CONTENT));
						newLL.setOrientation(LinearLayout.HORIZONTAL);
						newLL.setGravity(Gravity.LEFT);

						widthSoFar = 0;

						newLL.addView(allViews.get(i), par);

						allViews.get(i).measure(0, 0);
						widthSoFar += allViews.get(i).getMeasuredWidth();
					} else {
						newLL.addView(allViews.get(i), par);
					}
				}

				LLFavColorsHolder.addView(newLL);
/*
				if (allViews != null) {
					int i = 0;
					for (View v : allViews) {
						i += 1;
						LLFavColorsHolder.addView(v);
						Log.d("", "== added view: " + String.valueOf(i));
					}

					Log.d("", "== added all views, size:" + allViews.size());
				}
*/
				/*
				 * if (progress.isShowing()) progress.dismiss();
				 */
			} catch (Exception ex) {
				ex.printStackTrace();
			}
/*			while(true){
				if(didAddColor){
					didAddColor=false;
					
					View v= new View(getContext());
					LinearLayout.LayoutParams par=new LinearLayout.LayoutParams(50,50);
					par.setMargins(10, 0, 0, 10);
					//v.setLayoutParams(par);
					
					v.setBackgroundColor(favColors.get(favColors.size()-1).colorValue);
					v.setTag(favColors.size()-1);
					v.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							int x=(Integer) v.getTag();
							v1.setBackgroundColor(favColors.get(x).colorValue);
							
						}
					});
					
					if (newLL.getChildCount()==5) {
						LLFavColorsHolder.addView(newLL);
						Log.d("", "== a new row");

						newLL = new LinearLayout(getContext());
						newLL.setLayoutParams(new LayoutParams(
								LayoutParams.FILL_PARENT,
								LayoutParams.WRAP_CONTENT));
						newLL.setGravity(Gravity.LEFT);
						newLL.setOrientation(LinearLayout.HORIZONTAL);

						newLL.addView(v, par);

					} else {
						newLL.addView(v, par);
					
				}
					
				}
			}*/
			
		}

	};

	public int getColor() {
	
		Bitmap viewCapture = Utility.ViewToBitmap(v1);
		int pixel = viewCapture.getPixel(10,10);
		return pixel;
	}

	LinearLayout newLL = new LinearLayout(getContext());

}
